﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media.Media3D;
using HelixToolkit.Wpf;
using 数字孪生Demo.Model3D;

namespace 数字孪生Demo.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {

        private object selectedObject;

        public object SelectedObject
        {
            get { return selectedObject; }
            set
            { 
                OnPropertyChanged(ref selectedObject, value);
            }
        }

        public void ViewPort_MouseLeftButtonDown(object sender,MouseButtonEventArgs e)
        {
            HelixViewport3D? helixViewport3D = sender as HelixViewport3D;
            Viewport3DHelper.HitResult? hitResult = helixViewport3D.Viewport.FindHits(e.GetPosition(helixViewport3D)).FirstOrDefault();
            
            if(SelectedObject != null && SelectedObject is VisualObject3D visual)
            {
                visual.OnSelected(false);
            }
            if (hitResult == null)
                return;
            // 如果点击的不是VisualObject3D，则清除选中状态
            if (hitResult.Visual is VisualObject3D visualObject)
            {
                SelectedObject = visualObject;
                visualObject.OnSelected(true);
            }
            else
            {
                SelectedObject = null;
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged<T>(ref T oldVal,T newVal,[CallerMemberName] string propertyName = "")
        {
            if(EqualityComparer<T>.Default.Equals(oldVal, newVal))
                return;
            oldVal = newVal;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
